package com.liubujun.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author: liubujun
 * @Date: 2022/2/13 14:05
 */


public class ServerSocketChannelDemo {
    public static void main(String[] args) throws Exception {
        //端口号
        int port = 8888;

        ByteBuffer buffer = ByteBuffer.wrap("hello wrold".getBytes());
        //打开ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        //绑定
        ssc.socket().bind(new InetSocketAddress(port));
        //设置非阻塞模式
        ssc.configureBlocking(false);

        while (true) {
            System.out.println("正在等待链接");
            //监听新进的链接
            SocketChannel sc = ssc.accept();
            if (sc == null ) {
                System.out.println("null");
                Thread.sleep(2000);
            }else {
                System.out.println("链接来自:"+sc.socket().getRemoteSocketAddress());
                buffer.rewind(); //指针0
                sc.write(buffer);
                sc.close();
            }
        }
    }
}
